package com.atguigu.gmall.order.listener;

import com.atguigu.gmall.order.service.OrderService;
import com.rabbitmq.client.Channel;
import lombok.extern.log4j.Log4j2;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * projectName: gmall
 *
 * @author: 陈鹏
 * time: 2022/10/15 14:46 星期六
 * description: 订单支付消息监听的消费者
 */
@Component
@Log4j2
public class OrderPayListener {

    @Autowired
    private OrderService orderService;
    /**
     * 监听支付结果消息,修改订单的支付状态
     * @param channel
     * @param message
     */
    @RabbitListener(queues = "pay_order_queue")
    public void orderPayListener(Channel channel, Message message){
        //获取消息的属性
        MessageProperties messageProperties = message.getMessageProperties();
        //获取消息的编号
        long deliveryTag = messageProperties.getDeliveryTag();
        //获取消息体(支付结果 JSON字符串)
        String s = new String(message.getBody());
        try {
            //修改订单的支付状态
            orderService.updateOrder(s);
            //确认消息
            channel.basicAck(deliveryTag,false);
        }catch (Exception e){
            try {
                if(messageProperties.getRedelivered()){
                    //拒绝过则保存到日志,消息拒绝消费并丢弃
                    log.error("修改订单的支付结果两次失败,支付报文为:" + s);
                    channel.basicReject(deliveryTag,false);
                }else{
                    //看消息是否被拒绝过,没有拒绝过再来一次
                    channel.basicReject(deliveryTag,true);
                }
            }catch (Exception e1){
                log.error("拒绝消息失败,修改订单的支付结果失败,支付报文为: " + s);
            }
        }
    }
}
